import { Anchor, Avatar, Flex, Group } from "@mantine/core";
import { useAPIUtils } from "./APIUtilsProvider";

export default function ProductPill({ product, productId }) {
  if (product) {
    return (
      <Flex>
        <Group
          gap={"xs"}
          style={(theme) => ({
            backgroundColor: theme.colors.gray[1],
            borderRadius: "16px",
          })}
        >
          <Avatar src={product.meta.imageUrl} alt={product.name} size={"sm"} />

          <Anchor
            href={`/products/${product.id}`}
            target="_blank"
            size="sm"
            pr={8}
          >
            {product.name}
          </Anchor>
        </Group>
      </Flex>
    );
  } else if (productId) {
    return <ProductPillAsync productId={productId} />;
  } else {
    return <></>;
  }
}

function ProductPillAsync({ productId }) {
  const { tanstackQuery } = useAPIUtils();
  const productQuery = tanstackQuery(`/api/products/${productId}`);
  if (!productQuery.data) {
    return <></>;
  }

  const product = productQuery.data;

  return (
    <Group
      gap={"xs"}
      style={(theme) => ({
        backgroundColor: theme.colors.gray[1],
        borderRadius: "16px",
      })}
    >
      <Avatar src={product.meta.imageUrl} alt={product.name} size={"sm"} />

      <Anchor href={`/products/${product.id}`} target="_blank" size="sm" pr={8}>
        {product.name}
      </Anchor>
    </Group>
  );
}
